package com.mingqijia.gassafety.shared.utils.commonUtils;

import com.gap.basic.exception.BizException;
import org.apache.commons.lang.NullArgumentException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 文件导入
 *
 * @author wanghai
 * @since 2022-02-18
 */

public class FileUploadUtils {

    /**
     * 将file文件转为 List<map>数据
     * @param file
     * @return
     * @throws Exception
     */
    public static ArrayList<Map<String, String>> uploadExcel(MultipartFile file){
        //导入为list
        ArrayList<Map<String, String>> data = new ArrayList<>();
        try {
            if (file == null || file.getOriginalFilename() ==null) {
                throw new BizException("文件或文件名不能为空.");
            }
            InputStream inputStream = file.getInputStream();
            String filename = file.getOriginalFilename();

            Workbook workbook = null;
            // 调用解析文件方法
            if (filename.endsWith(".xls")) {
                workbook = new HSSFWorkbook(inputStream);
            }
            // xlsx是高版本的Excel文件
            if (filename.endsWith(".xlsx")) {
                workbook = new XSSFWorkbook(inputStream);
            }
            if (workbook == null) {
                throw new BizException( "文件格式不兼容,必须为 .xls,.xlsx" );
            }
            // 取到excel 中的第一张工作表
            Sheet sheet = workbook.getSheetAt(0);
            //第一行
            Row title = sheet.getRow( 0 );
            //获得当前行的列数
            int lastCellNum = title.getPhysicalNumberOfCells();
            //从第二行遍历到结束
            for (int rowNum=1; rowNum < sheet.getLastRowNum(); rowNum++){
                Row row = sheet.getRow( rowNum );
                if(row ==null){
                    continue;
                }
                HashMap<String, String> rowMap = new HashMap<>();
                for (int i = 0; i<lastCellNum ; i++){
                    rowMap.put( title.getCell( i ).getStringCellValue(), row.getCell( i ).getStringCellValue());
                }
                data.add( rowMap );
            }
            return data;
        } catch (IOException e) {
            throw new BizException(  e.getMessage());
        }

    }
}
